package com.helloandroid.activitys

import android.widget.ImageButton
import android.widget.TextView
import androidx.activity.viewModels
import com.github.mikephil.charting.charts.BarChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.XAxis.XAxisPosition
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.*
import com.github.mikephil.charting.formatter.ValueFormatter
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.helloandroid.AppUtil
import com.helloandroid.R
import com.helloandroid.base.BaseActivity
import com.helloandroid.models.BsRecord
import com.helloandroid.models.BsRecordViewModel
import com.helloandroid.tools.AppConfig
import com.helloandroid.tools.GUtils
import com.helloandroid.tools.MyLog
import com.helloandroid.tools.MyTimeUtils
import com.helloandroid.view.CircleView
import dai.common.util.CommonUtils
import java.text.DecimalFormat
import kotlin.collections.ArrayList

class BuShuRecordActivity : BaseActivity() , OnChartValueSelectedListener {

    companion object {
        const val SizePerPage = 8
    }

    // views
    lateinit var chart: BarChart
    lateinit var tvDistance:TextView
    lateinit var tvSpendTime:TextView
    lateinit var tvEnergy:TextView
    lateinit var tvInfo:TextView
    lateinit var tvBs:TextView
    lateinit var circleView:CircleView

    val model: BsRecordViewModel by viewModels()

    var fullDatas:ArrayList<BsRecord> = ArrayList()
    var isReady = false

    override fun getContentViewResId() = R.layout.activity_bs_record

    override fun initView() {
        chart = findViewById(R.id.chart)
        tvDistance = findViewById(R.id.tvDistance)
        tvSpendTime = findViewById(R.id.tvSpendTime)
        tvEnergy = findViewById(R.id.tvEnergy)
        tvInfo = findViewById(R.id.tvInfo)
        tvBs = findViewById(R.id.tvBs)
        circleView = findViewById(R.id.circleView)

        findViewById<ImageButton>(R.id.ibBack).setOnClickListener {
            finish()
        }

        initChar()
    }

    private fun initChar(){

        // 添加一组为0的数据
        val dayTimeInt = MyTimeUtils.timeToInt(AppUtil.sysTime)
        for (i in 0 until SizePerPage - 1){
            val t = SizePerPage - 1 - i
            val dayInt = MyTimeUtils.moveDayInt(dayTimeInt,-t)
            fullDatas.add(BsRecord(dayInt,CircleView.DefaultTarget, 0))
        }

        // 今天的数据
        fullDatas.add(BsRecord(dayTimeInt,AppUtil.user.bs_target, AppUtil.user.bs))

        // apply styling
        chart.description.isEnabled = false
        chart.setDrawGridBackground(false)
        chart.setDrawBarShadow(false)

        //------------------------------------------
        // 交互设置
        chart.isScaleYEnabled = false
        val ratio = (fullDatas.size.toFloat()) / SizePerPage
        MyLog.info("ratio:${ratio}")
        chart.zoom(ratio, 1f, 0f, 0f)
        chart.isScaleXEnabled = false

        // set data
        chart.data = generateDataBar(fullDatas)
//        chart.setFitBars(true)

        //----------------------------------
        // 在设置了数据后.  再设置 X 轴
        val xAxis: XAxis = chart.xAxis
        xAxis.position = XAxisPosition.BOTTOM
        xAxis.setDrawGridLines(false)
        xAxis.setDrawAxisLine(true)

        //设置为true当一个页面显示条目过多，X轴值隔一个显示一个
        xAxis.isGranularityEnabled = true

        xAxis.valueFormatter = object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                // 只返回今天的
                val idx = value.toInt()

                // 感觉是库的bug
                if (idx >= fullDatas.size){
                    return super.getFormattedValue(value)
                }
                val mdstr = fullDatas[idx].daiTimeInt.toString().substring(4)
                return "${mdstr.substring(0, 2)}/${mdstr.substring(2)}"
            }
        }

        // 左边的 Y 轴
        val leftAxis: YAxis = chart.axisLeft
        leftAxis.setLabelCount(5, false)
        leftAxis.axisMaximum = 10000f
        leftAxis.spaceTop = 20f
        leftAxis.axisMinimum = 0f // this replaces setStartAtZero(true)

        // 隐藏右边的 Y 轴
        chart.axisRight.isEnabled = false

        // 动画出现
        chart.animateY(700)

        // 显示最后一页
        moveToLast()

        installChartEvent()

        initInfos()
    }

    private fun moveToLast(){
        // 显示最后一页
        val count = fullDatas.size - SizePerPage + 1
        val clampedCount = CommonUtils.clampInt(count, 0, Int.MAX_VALUE)
        chart.moveViewToX(clampedCount.toFloat())
    }

    override fun initData() {

        //---------------------------------
        model.getInfo { success, lstDatas ->
            isReady = success
            if (success) {
                val lstRecords = lstDatas!!

                // 添加今天的数据
                val dayTimeInt = MyTimeUtils.timeToInt(AppUtil.sysTime)
                lstRecords.add(BsRecord(dayTimeInt, AppUtil.user.bs_target, AppUtil.user.bs))
                updateUI(lstRecords)
            }
        }
    }

    private fun generateDataBar(lst: List<BsRecord>): BarData {
        val entries = ArrayList<BarEntry>()
        for (i in lst.indices) {
            val item = lst[i]
            val barEntry = BarEntry(i.toFloat(), item.bs.toFloat())
            entries.add(barEntry)
        }
        MyLog.info("entries.size:${entries.size}")
        val d = BarDataSet(entries, "每日步数")
        //d.setColors(*ColorTemplate.VORDIPLOM_COLORS)
        d.color = resources.getColor(R.color.chart_normal_color,null)
        d.highLightColor = resources.getColor(R.color.chart_select_color,null)
        d.highLightAlpha = 255
        val cd = BarData(d)
        cd.barWidth = 0.4f
        return cd
    }

//    private fun genEmptyDataBar():BarData{
//        val entries = ArrayList<BarEntry>()
//        val barEntry = BarEntry(0f, AppUtil.user.bs.toFloat())
//        entries.add(barEntry)
//        MyLog.info("entries.size:${entries.size}")
//        val d = BarDataSet(entries, "每日步数")
//        //d.setColors(*ColorTemplate.VORDIPLOM_COLORS)
//        d.color = resources.getColor(R.color.chart_normal_color,null)
//        d.highLightColor = resources.getColor(R.color.chart_select_color,null)
//        d.highLightAlpha = 255
//        val cd = BarData(d)
//        cd.barWidth = 0.4f
//        return cd
//    }


    fun updateUI(lstRecords:ArrayList<BsRecord>) {

        // for test
        if (AppConfig.isDebug) {
            MyLog.info("=======================================")
            lstRecords.forEach { it ->
                MyLog.info(it.toString())
            }
            MyLog.info("=======================================")
            MyLog.info("lst.size:${lstRecords.size}")
        }

        // 填充缺少的
        model.fill(lstRecords,fullDatas){
            val fullList = fullDatas
            val barData = generateDataBar(fullList)
            if (AppConfig.isDebug) {
                MyLog.info("fullList.size:${fullList.size}")
            }

            // set data
            chart.data = barData

            // 重新设置缩放
            val ratio = (fullDatas.size.toFloat()) / SizePerPage
            MyLog.info("ratio:${ratio}")
            chart.zoom(ratio, 1f, 0f, 0f)

            chart.notifyDataSetChanged()
            moveToLast()

            initInfos()
        }
    }

    private fun installChartEvent() {
        chart.setOnChartValueSelectedListener(this)
    }

    override fun onValueSelected(e: Entry, h: Highlight?) {
        if (!isReady){
            return
        }
        val idx = e.x.toInt()
        val data = fullDatas!![idx]
        GUtils.updateDistanceAndEnergyUI(data.bs,tvDistance,tvSpendTime,tvEnergy)
        updateTextInfo(data)
    }

    override fun onNothingSelected() {
        circleView.animTo(0,CircleView.DefaultTarget)
    }

    private fun initInfos(){
        // 获取今天的数据
        val last = fullDatas!!.last()
        GUtils.updateDistanceAndEnergyUI(last.bs,tvDistance,tvSpendTime,tvEnergy)

        // 高亮今天数据
        val lastIdx = fullDatas!!.size - 1
        chart.highlightValue(lastIdx.toFloat(),0,false)

        // 更新信息
        updateTextInfo(last)
    }

    private fun updateTextInfo(item:BsRecord){
        val percent = (item.bs.toFloat() / item.target) * 100f
        val dec = DecimalFormat("00.00")
        val percentText = dec.format(percent)
        tvInfo.text = "完成${percentText}%,目标步数${item.target}"

        tvBs.text = "${item.bs}步"
        circleView.animTo(item.bs,item.target)
    }
}